#include "CircleItem.h"

#include <QtQuick/qsgnode.h>
#include <QtQuick/qsgflatcolormaterial.h>
#include <math.h>

CircleItem::CircleItem(QQuickItem *parent)
  : ShapeItem(parent)
  , m_center(0, 0)
  , m_radius(0.0)
  , m_segmentCount(128)
{
    setFlag(ItemHasContents, true);
}

void CircleItem::setCenter(const QPointF &cen)
{
    if (cen == m_center)
        return;

    m_center = cen;
    emit centerChanged(cen);
    update();
}

void CircleItem::setRadius(float r)
{
    if (r == m_radius)
        return;

    m_radius = r;
    emit radiusChanged(r);
    update();
}

void CircleItem::setSegmentCount(int count)
{
    if (count == m_segmentCount)
        return;

    m_segmentCount = count;
    emit segmentCountChanged(count);
    update();
}

QSGNode *CircleItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
{
    QSGGeometryNode *node = 0;
    QSGGeometry *geometry = 0;

    if (!oldNode) {
        node = new QSGGeometryNode;
        geometry = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), m_segmentCount);
        geometry->setLineWidth(1);
        geometry->setDrawingMode(GL_LINE_STRIP);
        node->setGeometry(geometry);
        node->setFlag(QSGNode::OwnsGeometry);

        QSGFlatColorMaterial *material = new QSGFlatColorMaterial;
        material->setColor(QColor(255, 255, 0));
        node->setMaterial(material);
        node->setFlag(QSGNode::OwnsMaterial);

    } else {
        node = static_cast<QSGGeometryNode *>(oldNode);
        geometry = node->geometry();
        geometry->allocate(m_segmentCount);
    }


    QSGGeometry::Point2D *vertices = geometry->vertexDataAsPoint2D();
    for (int i = 0; i < m_segmentCount; ++i) {
        qreal t = i / qreal(m_segmentCount - 1);



        float x = m_center.x() + m_radius * cos(t * M_PI * 2);
        float y = m_center.y() + m_radius * sin(t * M_PI * 2);

        vertices[i].set(x, y);
    }
    node->markDirty(QSGNode::DirtyGeometry);

    return node;
}
